package com.hmall.trade.listener;

import cn.hutool.core.util.ObjUtil;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import com.hmall.trade.service.impl.OrderServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class PayStatusListener {


    private final IOrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            // 队列的命名规则 消费者.生产者.业务场景.queue  durable 是否持久化
            value = @Queue(value = "trade.pay.success.queue",durable = "true"),
            // 交换机的命名规则 生产者.交换机类型
            exchange = @Exchange(name = "pay.direct"),
            // 路由键 生产者.业务场景
            key = "pay.success"
    ))
    public void listenPaySuccess(Long payOrderId) {
        // 1.查询支付单
        Order order = orderService.getById(payOrderId);

        // 2.判断支付单状态
        if (ObjUtil.isEmpty(order) || order.getStatus() != 1) {
            // 支付单不存在或者支付单状态不正确
            return;
        }


        //3. 标记订单已支付
        orderService.markOrderPaySuccess(payOrderId);
    }
}
